//  this library.
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:hktk_app/ienum/question/first_type_enum.dart';
import 'package:hktk_app/ienum/question/question_type_enum.dart';
import 'package:hktk_app/model/question/question_data_model.dart';
import 'package:hktk_app/util/event_bus_util.dart';
import 'package:hktk_app/util/font_util.dart';
import 'package:hktk_app/util/my_util.dart';
import 'package:hktk_app/util/sz_util.dart';
import 'package:hktk_app/util/view_util.dart';

typedef StemTextFun = void Function(bool change, List<String> list);

/// 输入框显示组件
class StemTextWidget extends StatefulWidget {
  /// 试题对应id
  final String qId;

  /// 答案相关数据
  final List<String> answer;

  /// 选项相关数据
  final List<OptionModel> opList;

  /// 试题类型
  final FirstTypeEnum qType;

  /// 试题模式，ture-答题，false-背题
  final QuestionTypeEnum type;

  /// 是否显示答案
  final bool showDa;

  /// 返回填入值方法
  final StemTextFun onTapFunQd;

  /// 用户答案是否改变
  final bool ansChange;

  const StemTextWidget({
    super.key,
    required this.qId,
    required this.answer,
    required this.opList,
    required this.qType,
    required this.showDa,
    required this.onTapFunQd,
    required this.type,
    required this.ansChange,
  });

  @override
  State<StemTextWidget> createState() => _StemTextWidgetState();
}

class _StemTextWidgetState extends State<StemTextWidget> {
  /// 内容是否发生改变
  late bool _change;

  /// 输入框相关控制器
  late List<TextEditingController> _controllerList;

  /// 输入框焦点控制
  late List<FocusNode> _focusList;

  /// 填空题长度
  late int _tktLength;

  /// 监听选项
  late StreamSubscription<EventQuestionOnOpt> _eventOpt;

  @override
  void initState() {
    super.initState();
    debugPrint("stemTextWidget 组件 -> initState 方法执行 ===> ");
    debugPrint("");
    if (MyUtil.getTKT(widget.qType)) {
      if (widget.answer.isNotEmpty) {
        _tktLength = widget.answer.length;
      } else {
        _tktLength = widget.opList.length;
      }
    } else {
      _tktLength = 1;
    }
    // 创建控制器
    _controllerList = [];
    _focusList = [];
    for (int i = 0; i < _tktLength; i++) {
      _controllerList.add(TextEditingController());
      _focusList.add(FocusNode());
    }

    // 监听是否点击了确定
    _eventOpt = eventBus.on<EventQuestionOnOpt>().listen((event) {
      debugPrint(
          "stemTextWidget 组件 -> 监听是否点击确定方法执行 ===> ${event.qId} , wqid : ${widget.qId}");
      if (event.qId == widget.qId) {
        List<String> list = _getList();
        debugPrint("change ===> $_change");
        widget.onTapFunQd(_change, list);
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    debugPrint("stemTextWidget 组件 -> dispose 方法执行 ===> ");
    debugPrint("");
    for (int i = 0; i < _tktLength; i++) {
      _controllerList[i].dispose();
      _focusList[i].dispose();
    }
    _eventOpt.cancel();
  }

  @override
  Widget build(BuildContext context) {
    debugPrint("stemTextWidget 组件 -> build 方法执行 ===> ${widget.ansChange}");
    debugPrint("");
    _change = widget.ansChange;
    return Column(
      children: _items(),
    );
  }

  /// 相关组件显示
  _items() {
    if (MyUtil.getTKT(widget.qType)) {
      return tktItems();
    } else if (MyUtil.getWDT(widget.qType)) {
      return [_wdtItem()];
    }
  }

  /// 填空题相关输入框实现
  tktItems() {
    List<Widget> widgets = [];
    for (int i = 0; i < _tktLength; i++) {
      widgets.add(_tktItem(i));
      if (i != _tktLength - 1) {
        widgets.add(hiSpace(height: 50));
      }
    }
    return widgets;
  }

  /// 填空题组件
  _tktItem(int index) {
    return _textItem(
      index: index,
      tips: _getTktTips(index),
    );
  }

  String _getTktTips(int index) {
    if (widget.type == QuestionTypeEnum.answer ||
        widget.type == QuestionTypeEnum.exam) {
      return "请输入填空${index + 1}";
    } else {
      return widget.answer[index];
    }
  }

  /// 输入框组件
  _textItem({
    required int index,
    required String tips,
    int? maxLinesV = 1,
    int? minLinesV,
  }) {
    double fontSizeV = szUtilComm.szInfo.getZtdxPx()!;
    return TextField(
      controller: _controllerList[index],
      // 焦点控制
      focusNode: _focusList[index],
      // 设置光标颜色
      cursorColor: getColorBlue1(szYjms: szUtilComm.szInfo.yjms),
      // 光标高度
      cursorHeight: fontSizeV + 14,
      // 样式
      style: FontUtil.fontGrey2(fontSizeV),
      // 最多行数
      maxLines: maxLinesV,
      // 最小行数
      minLines: minLinesV,
      // 内容改变时监听
      onChanged: (value) {
        if (!_change) {
          _change = true;
        }
      },
      // 装饰
      decoration: InputDecoration(
        // 去掉textField自定的高度
        isCollapsed: true,
        // 提示语句
        hintText: tips,
        // 提示语句样式
        hintStyle: FontUtil.fontGrey2(fontSizeV),
        // 内边距
        contentPadding: EdgeInsets.all(24),
        // 正常情况下的border边框
        border: OutlineInputBorder(
          borderSide: BorderSide(color: colorGrey6, width: 2),
          borderRadius: BorderRadius.circular(20),
        ),
        // 输入框可用时显示的边框
        enabledBorder: OutlineInputBorder(
          borderSide: BorderSide(color: colorGrey6, width: 2),
          borderRadius: BorderRadius.circular(20),
        ),
        // 输入框有焦点时的边框
        focusedBorder: OutlineInputBorder(
          borderSide: BorderSide(color: colorGrey6, width: 2),
          borderRadius: BorderRadius.circular(20),
        ),
        // 输入框是否可用
        enabled:
        widget.type == QuestionTypeEnum.answer ? !widget.showDa : false,
      ),
    );
  }

  /// 获取填入值方法
  List<String> _getList() {
    List<String> list = [];
    for (int i = 0; i < _tktLength; i++) {
      list.add(_controllerList[i].text);
      _focusList[i].unfocus();
    }
    return list;
  }

  /// 问答题输入框显示
  Widget _wdtItem() {
    return _textItem(
      index: 0,
      tips: "请输入答案",
      maxLinesV: 8,
      minLinesV: 3,
    );
  }
}
